<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2021/7/20
 * Time: 4:20 下午
 */

namespace app\api\controller\v1;


use app\api\model\SjMsg as SjMsgModel;
use app\api\model\SjMsgImg;
use LinCmsTp5\exception\ParameterException;
use think\Db;
use think\facade\Log;
use think\facade\Request;

class SjMsg
{
    /**
     * 获取全部
     */
    public function getDataAll()
    {
        return SjMsgModel::with('imgs.img')->order('id desc')->select()->toArray();
    }

    /**
     * 获取列表
     * @validate('PagingParameter')
     * @auth('查看活动商家','活动商家管理')
     */
    public function getDataList($title,$page,$limit)
    {
        $where = [];
        if($title) {
            $where[] = ['title','like','%'.$title.'%'];
        }
        $query = SjMsgModel::where($where)->with('imgs.img')->order('order_sort desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取详情
     * @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        return SjMsgModel::where('id',$id)->with('imgs.img')->find();
    }


    /**
     * 修改信息
     * @validate('CheckSjMsg')
     */
    public function updateData($id,$title,$img_ids, $point, $address,$content)
    {
        Db::startTrans();
        try {
            $info = SjMsgModel::get($id);
            if ($info) {
                $info->title = $title;
                $info->point = $point;
                $info->address = $address;
                $info->content = $content;
                $info->save();
                SjMsgImg::destroy([
                    'msg_id' => $id
                ]);
                $img_data = [];
                foreach ($img_ids as $k=>$v){
                    $img_data[$k] = [
                        'img_id'=>$v['imgId'],
                        'msg_id' => $info->id
                    ];
                }
                $GfActivityImg = new SjMsgImg();
                $GfActivityImg->allowField(true)->saveAll($img_data);
            }
            Db::commit();
            return writeJson(202, [], '修改成功！');
        }catch (\Exception $e){
            Log::init([
                'type' => 'File'
            ]);
            Log::write(Request::url()+'-put-'.$e,'error');
            throw new ParameterException([
                'msg' => [
                    'product' => '添加失败!'
                ]
            ]);
        }
    }

    /**
     * 总管理修改信息
     */
    public function updateDataAdmin($id,$order_sort,$status,$openid)
    {
        $info = SjMsgModel::get($id);
        if ($info) {
            $info->order_sort = $order_sort;
            $info->status = $status;
            $info->openid = $openid;
            $info->save();
        }
        return writeJson(202, [], '修改成功！');
    }
}